import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

# 设置中文字体（这里以黑体为例，你可以根据实际情况选择合适的字体路径和字体名称）
font = FontProperties(fname=r'c:\windows\fonts\simhei.ttf', size=14)
plt.rcParams['font.family'] = font.get_family()
plt.rcParams['font.sans-serif'] = font.get_name()


def sum_second_numbers(file_path):
    try:
        with open(file_path, 'r') as file:
            lines = file.readlines()
            total = 0
            for line in lines:
                numbers = line.strip().split(',')
                second_number = int(numbers[1])
                total += second_number
        return total
    except FileNotFoundError:
        print(f"错误：未找到文件 {file_path}")
        return None
    except IndexError:
        print(f"错误：文件 {file_path} 中的某些行格式不正确，无法提取第二个数字。")
        return None
    except ValueError:
        print(f"错误：文件 {file_path} 中的某些行包含无法转换为整数的内容。")
        return None
    except Exception as e:
        print(f"发生未知错误：{e}")
        return None


# 定义四个文件的路径
file_paths = [
    r"D:\low\platform\Low-altitude multi-agent hierarchical path planning experimental platform\data\obstacle\Buffer_layer.txt",
    r"D:\low\platform\Low-altitude multi-agent hierarchical path planning experimental platform\data\obstacle\Layered_CBS.txt",
    r"D:\low\platform\Low-altitude multi-agent hierarchical path planning experimental platform\data\obstacle\metropolis.txt",
    r"D:\low\platform\Low-altitude multi-agent hierarchical path planning experimental platform\data\obstacle\Six_layers.txt"
]

sums = []
# 提取文件名
file_names = [
    "Buffer_layer",
    "Layered_CBS",
    "metropolis Ⅱ",
    "Six_layers"
]

for file_path in file_paths:
    total = sum_second_numbers(file_path)
    if total is not None:
        sums.append(total)

# 绘制条形图
if sums:
    # 定义不同的颜色列表
    colors = ['red', 'green', 'blue', 'orange']
    # 设置条形图的宽度，使其更瘦高
    bar_width = 0.4
    bars = plt.bar(file_names, sums, width=bar_width, color=colors)
    plt.xlabel('文件')
    plt.ylabel('每行第二个数字之和')
    plt.title('算法性能指标对比')

    # 计算并打印第二个数据比其他数据提高的比例
    second_value = sums[1]
    for i, value in enumerate(sums):
        if i != 1:
            percentage = ((second_value - value) / value) * 100 if value != 0 else 0
            print(f"{file_names[1]} 比 {file_names[i]} 提高了 {percentage:.2f}%")

    # 在每个条形图上方标注文件名（这里其实文件名已经在x轴上，此步骤可根据实际需求决定是否保留）
    for bar, name in zip(bars, file_names):
        yval = bar.get_height()
        plt.text(bar.get_x() + bar.get_width() / 2, yval + 0.05 * max(sums), name, ha='center', va='bottom')

    plt.show()